package cc.telecomdigital.tdstock.Services;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

//Check whether the device still could use the free tail;
public class TDStockReqFreeVerify
{

	static public interface ITDStockReqFreeVerify_Result
	{
		void TDStockReqFreeVerify_Response(TDStockReqFreeVerify_Result iResult);
	}

	static public class TDStockReqFreeVerify_Result
	{
		public boolean	successfulSend;
		public String	errorMessage;
		public String	statusCode;

		/** iSuccessfulSend == whether it has been sent
		    iStatus == server report status if successfully send
		    iErrorMessage = server response Message if successfully send **/
		public TDStockReqFreeVerify_Result(boolean iSuccessfulSend,
				String iStatus, String iErrorMessage)
		{
			successfulSend = iSuccessfulSend;
			errorMessage = iErrorMessage;
			statusCode = iStatus;
		}
	}

	private final int					FREE_TRAIL_VERIFY	= 1;
	// The reply mostly will be handled by UI, free for developer
	private Handler					localMsgHandler	= new Handler()
													{
														// Need to use try and catch
														public void handleMessage(
																Message msg)
														{
															switch (msg.what)
															{
																case FREE_TRAIL_VERIFY:
																	if (reporter != null)
																		reporter.TDStockReqFreeVerify_Response((TDStockReqFreeVerify_Result) msg.obj);
																	break;
															}
														}
													};

	private final String				LOG_TAG		= "TDStockReqFreeVerify";

	private String						urlString;
	@SuppressWarnings("unused")	
	private String						urlPort;
	private ITDStockReqFreeVerify_Result	reporter;
	private final int					SOCKET_TIMEOUT		= 30000;
	private final int					CONNECT_TIMEOUT	= 30000;
	private Context					ownerContext;
	private final boolean                   debugMode = false;
	private final int                       trialMax = 2;

	/** With fill in url and request item, create an object to request for Register for free trial
	    The Url should include a Access Code **/
	public TDStockReqFreeVerify(Context iOwner, String iURL, String iPortNum)
	{
		ownerContext = iOwner;
		urlString = iURL;
		urlPort = iPortNum;
	}

	/** Send a Request for the free access **/
	public void SendRequest(ITDStockReqFreeVerify_Result iReporter)
	{
		reporter = iReporter;
		Thread internalThreadObj = new Thread()
		{
			@Override
			public void run()
			{
				if (!DeviceInfo.IsNetworkAvailable(ownerContext)
						|| (urlString == null))
				{
					Message newMessage;

					newMessage = new Message();
					newMessage.what = FREE_TRAIL_VERIFY;

					newMessage.obj = new TDStockReqFreeVerify_Result(
											false, null, null);
					localMsgHandler.sendMessage(newMessage);
					return;
				}
				
				int trialCount;
				
				//Now send the result				
				HttpClient 			   client;
				HttpGet 				   request;
				HttpParams 			   modParams;
				TDStockReqFreeVerify_Result result;				

				client    = new DefaultHttpClient();
				request   = new HttpGet(urlString);
				modParams = request.getParams();

				// Change the setting
				HttpConnectionParams.setSoTimeout(modParams, SOCKET_TIMEOUT);
				HttpConnectionParams.setConnectionTimeout(modParams, CONNECT_TIMEOUT);
				request.setParams(modParams);				
				
				trialCount = 0;
				while(true)
				{					
					result = SendDataSub(client, request);
					//If we did not get the require login information
					if ((result.errorMessage == null) && (result.statusCode == null) )
					{
						++trialCount;
						if (trialCount < trialMax)
						{
							if (debugMode)
								TDStockLog.i(LOG_TAG, "SendRequest: Retry performed: " + trialCount);
							try
							{
								sleep(200);
							}
							catch(Exception ex)
							{
								TDStockLog.e(LOG_TAG, "SendRequest: Ex=" + ex.toString());
							}							
							continue;
						}
					}					
					
					Message newMessage;

					newMessage = new Message();
					newMessage.what = FREE_TRAIL_VERIFY;
					newMessage.obj = result;
					localMsgHandler.sendMessage(newMessage);					
					break;
				}			
			}			
		};
		internalThreadObj.start();
	}

	private TDStockReqFreeVerify_Result SendDataSub(HttpClient iClient, HttpGet iRequest)
	{
		String statusMsg, errorMsg;
		
		statusMsg = null;
		errorMsg = null;

		try
		{
			HttpResponse webResponse;
			StringBuffer contentString;

			webResponse = iClient.execute(iRequest);
			if ((webResponse == null) || (webResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK ))
				webResponse.getEntity().getContent().close();
			else
			{
				contentString = CommunicTools.GetWebResponseInStringBuffer(webResponse);						
				statusMsg = CommunicTools.FindXMLStringContent(contentString, "Status");
				errorMsg = CommunicTools.FindXMLStringContent(contentString, "ErrorMessage");
			}				
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();			
			TDStockLog.e(LOG_TAG, "SendDataSub: " + e.toString());
		}
		catch (IOException e)
		{
			e.printStackTrace();			
			TDStockLog.e(LOG_TAG, "SendDataSub: " + e.toString());
		}

		return new TDStockReqFreeVerify_Result(true, statusMsg, errorMsg);	
	}
}
